const mongoose = require('mongoose');
const Comment = require('../models/comment.model');

//自己建了一个函数,将users.js中的函数写道exports
exports.creat = function(req, res, next) {
    var comment = new Comment(req.body);
    comment.save().then(data => {
        //console.log(data);
        res.json(data); //以json形式进行数据返回
    })
};

//修改数据
exports.update = function(req, res, next) {
    const id = req.params.id;
    Comment.findByIdAndUpdate(id, { $set: req.body }).then(data => {
        res.json(data);
    })

};

//删除
exports.remove = function(req, res, next) {
    const id = req.params.id;
    Comment.findByIdAndRemove(id, (err, data) => {
        res.json(data);
    })
};

//查询
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5;
    var queryCondition = {};
    var cateId = req.body.cateId; //cateId是默认必填
    if (cateId === undefined) { //不是null
        res.json({ message: 'err message' });
        return;
    } else {
        queryCondition = {
            cateId: cateId
        }
    };


    if (req.body.title && req.body.title.trim().length > 0) {
        title = req.body.title;
        queryCondition = Object.assign(queryCondition, {
            title: new RegExp(title, 'i')

        });
    }
    Comment.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        // result.docs
        // result.total
        // result.limit - 10
        // result.page - 3
        // result.pages
        result.rows = result.docs;
        delete result.docs;
        res.json(result); //返回一个对象 “docs”，在post里面设置page页码和limit查看对应页码内容，不过limit是字符串类型的
    });

};

//获取数据
exports.get = function(req, res, next) {
    const id = req.params.id;
    Comment.findById(id).then(data => {
        res.json(data);
    })
}